const userService = require('../services/userService');

exports.register = async (req, res) => {
  try {
    let { username, password, real_name, nickname, phone, gender } = req.body;
    // 优先使用 nickname 作为 real_name
    if (nickname) real_name = nickname;
    if (!username || !password || !phone) return res.json({ code: 400, msg: '用户名、密码、手机号必填' });
    const result = await userService.register(username, password, real_name, phone, gender);
    if (!result.success) return res.json({ code: 400, msg: result.message });
    res.json({ code: 200, msg: '注册成功' });
  } catch (e) {
    res.json({ code: 500, msg: '注册失败' });
  }
};

exports.login = async (req, res) => {
  try {
    const { username, password } = req.body;
    // 新增：支持用旧token换新token
    const authHeader = req.headers['authorization'] || req.headers['Authorization'];
    if ((!username || !password) && authHeader && authHeader.startsWith('Bearer ')) {
      const oldToken = authHeader.split(' ')[1];
      const userInfo = userService.verifyToken(oldToken);
      if (!userInfo) return res.json({ code: 401, msg: 'token无效' });
      // 重新查库，防止用户已被禁用
      const user = await userService.getUserByUsername(userInfo.username);
      if (!user) return res.json({ code: 401, msg: '用户不存在' });
      const token = userService.signToken(user);
      return res.json({ code: 200, msg: '刷新token成功', data: { token } });
    }
    if (!username || !password) return res.json({ code: 400, msg: '用户名和密码必填' });
    const result = await userService.login(username, password);
    if (!result.success) return res.json({ code: 400, msg: result.message });
    res.json({ code: 200, msg: '登录成功', data: { token: result.token } });
  } catch (e) {
    res.json({ code: 500, msg: '登录失败' });
  }
};

exports.profile = (req, res) => {
  if (!req.user) return res.json({ code: 401, msg: '未登录' });
  res.json({ code: 200, msg: '获取成功', data: { user: req.user } });
};

exports.getAllUsers = async (req, res) => {
  try {
    const users = await userService.getAllUsers();
    res.json({ code: 200, msg: '获取成功', data: users });
  } catch (e) {
    res.json({ code: 500, msg: '获取用户失败' });
  }
};

// 实时校验手机号唯一性
exports.checkPhone = async (req, res) => {
  const { phone } = req.query;
  if (!phone) return res.json({ code: 400, msg: '手机号不能为空', data: { valid: false } });
  const exists = await userService.checkPhone(phone);
  res.json({ code: 200, msg: '校验成功', data: { valid: !exists } });
};

// 实时校验用户名唯一性
exports.checkUsername = async (req, res) => {
  const { username } = req.query;
  if (!username) return res.json({ code: 400, msg: '用户名不能为空', data: { valid: false } });
  const exists = await userService.checkUsername(username);
  res.json({ code: 200, msg: '校验成功', data: { valid: !exists } });
}; 